package com.skyline.search.search.impl;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import com.skyline.search.config.Config;
import com.skyline.search.config.ConfigItem;
import com.skyline.search.model.Page;
import com.skyline.search.model.ResultSet;
import com.skyline.search.search.SearchProxy;
import com.skyline.search.search.Searcher;

/**
 * Class <code>SearchProxyImpl</code> SearchProxyImpl是对SearchProxy的实现
 * 
 * @author Jairus Chan
 * @version 0.1, 11/30/10
 * @since JDK1.6
 */

public class SearchProxyImpl extends UnicastRemoteObject implements SearchProxy {
	
	private static final long serialVersionUID = 1L;
	
	Map<String, Searcher> searchers = new HashMap<String, Searcher>();

	public SearchProxyImpl(Config config) throws IOException, RemoteException {
		super();
		inital(config);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void inital(Config config) throws IOException, RemoteException {
		@SuppressWarnings("static-access")
		Map<String, ConfigItem> indexPathesMap = config.getConfigProperties();// .getIndexPathes();
		Iterator indexPathes = indexPathesMap.entrySet().iterator();
		while (indexPathes.hasNext()) {
			Map.Entry entry = (Map.Entry) indexPathes.next();
			String index = (String) entry.getKey();
			ConfigItem configItem = (ConfigItem) entry.getValue();
			Searcher searcher = new SearcherImpl();
			searcher.inital(configItem.getIndexpath());
			searchers.put(index, searcher);
		}
	}

	private Searcher getSearcher(String index) {
		return searchers.get(index);
	}

	@Override
	public ResultSet search(String queryString, Page page, String[] fields,
			Analyzer analyzer, String index) throws RemoteException {
		Searcher searcher = getSearcher(index);
		if (searcher == null) {
			ResultSet result = new ResultSet();
			result.setPage(page);
			List<Document> documents = new ArrayList<Document>();
			result.setDocuments(documents);
		}
		return searcher.search(queryString, page, fields, analyzer);
	}

	@Override
	public ResultSet searchWithStandardAnalyzer(String queryString, Page page,
			String[] fields, String index) throws RemoteException {
		Searcher searcher = getSearcher(index);
		return searcher.searchWithStandardAnalyzer(queryString, page, fields);
	}

	@Override
	public ResultSet searchWithDefaultAnalyzer(String queryString, Page page,
			String[] fields, String index) throws RemoteException {
		Searcher searcher = getSearcher(index);
		return searcher.searchWithDefaultAnalyzer(queryString, page, fields);
	}

}
